package com.cms.security;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cms.support.SHA1Util;

public class LoginFilter implements Filter {
	private final static String  key = "88888888";
	/*
	 * private static final Logger LOGGER = LoggerFactory
	 * .getLogger(LoginFilter.class);
	 */

	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String servletPath = httpRequest.getServletPath();
		UserSession userSession = (UserSession) httpRequest.getSession()
				.getAttribute("userSession");

		// 从 HTTP 头中取得 Referer 值
		// String referer = httpRequest.getHeader("Referer");
		// LOGGER.info(referer+"-----------");
		if (userSession != null) {
			if (isStaticSource(servletPath)) {
				chain.doFilter(request, response);
			} else {
				chain.doFilter(request, response);
			}

		} else if (isStaticSource(servletPath)) {
			chain.doFilter(request, response);
		} else if (servletPath.contains("/api/")) {
			String userName = httpRequest.getParameter("userName");
			String sign = httpRequest.getParameter("sign");
			if (servletPath.contains("/error")) {
				chain.doFilter(request, response);
			}
			if (userName != null && sign != null
					&& sign.equals(SHA1Util.hex_sha1(userName + key))) {
				chain.doFilter(request, response);
			} else {
				httpResponse.sendRedirect("error");
			}
		} else {
			httpResponse
					.sendRedirect(httpRequest.getContextPath() + "/timeOut");
		}
	}

	private boolean isStaticSource(String servletPath) {
		if (servletPath.equals("/") || servletPath.equals("/login")
				|| servletPath.equals("/deny")
				|| servletPath.contains("/html")
				|| servletPath.equals("/timeOut")
				|| servletPath.equals("/j_spring_security_check")
				|| servletPath.equals("/common/createCode")
				|| servletPath.equals("/common/validateCode")
				|| servletPath.contains("/js/")
				|| servletPath.contains("/css/")
				|| servletPath.contains("/fonts/")
				|| servletPath.contains("/hplus/")
				|| servletPath.contains("/wxapi/")
				|| servletPath.contains("/portal")
				|| servletPath.contains("/images/")) {
			return true;
		} else {
			return false;
		}
	}

	public void destroy() {
	}

}